<template>
  <el-button plain type="primary" @click="handleAddGroup">
    新增分组
  </el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="groupName" label="分组名称" width="300"/>
    <el-table-column prop="groupDesc" label="分组描述" width="300"/>
    <el-table-column prop="createTime" label="创建时间" width="300"/>
    <el-table-column fixed="right" label="Operations" min-width="300">
      <template #default="scope">
        <el-button link type="primary" @click="handleUpdateGroup(scope)">
          编辑
        </el-button>
        <el-popconfirm title="是否确认删除?" @confirm="handleDeleteGroup(scope)">
          <template #reference>
            <el-button link type="primary">
              删除
            </el-button>
          </template>
        </el-popconfirm>
        <el-button link type="primary" @click="routerToFile(scope)">模板文件管理</el-button>
        <el-button link type="primary" @click="routerToVar(scope)">模板变量管理</el-button>
        <el-button link type="primary" @click="generate(scope)">
          生成
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500">
    <el-form :model="form">
      <el-form-item label="分组名称" :label-width="formLabelWidth">
        <el-input v-model="form.groupName" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="分组描述" :label-width="formLabelWidth">
        <el-input v-model="form.groupDesc" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGroupChange">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog v-model="generateFrame" title="代码生成" width="800">
    <el-form :model="generateForm">
      <div v-if="varListLoadingErrMsg">
        <el-form-item label="请输入json格式的对象" :label-width="formLabelWidth">
          <el-input
            v-model="varListLoadingErrVarData"
            style="width: 600px"
            :rows="3"
            type="textarea"
            placeholder="如果上传模板文件可以不填"
          />
        </el-form-item>
      </div>
      <div v-else>
        <el-form-item v-for="(item, index) in varList" :label="item.variableName"
                      :label-width="formLabelWidth">
          <el-input v-model="generateForm[item.variableName]" autocomplete="off"/>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="generateFrame = false">取消</el-button>
        <el-button type="primary" @click="submitGenerate">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {instance} from '@/api/base'
import {onMounted, reactive, ref} from 'vue'

import {useRouter} from 'vue-router'
import {listGroupVariableByGroupId} from '@/api/request'

const router = useRouter()

const generateFrame = ref(false)
const generateGroupId = ref('')
const varList = ref([])
const varListLoadingErrMsg = ref('')
const varListLoadingErrVarData = ref()

const tableData = ref([])
const dialogFormVisible = ref(false)
const formLabelWidth = ref('140px')
const formTitle = ref('')
const generateForm = ref({})
const form = reactive({
  pkid: '',
  groupName: '',
  groupDesc: '',
})
const handleAddGroup = () => {
  form.pkid = ''
  form.groupName = ''
  form.groupDesc = ''
  formTitle.value = '新增'
  dialogFormVisible.value = true
}

const handleUpdateGroup = (scope) => {
  const selectItem = tableData.value[scope.$index]
  form.pkid = selectItem.pkid
  form.groupName = selectItem.groupName
  form.groupDesc = selectItem.groupDesc
  formTitle.value = '编辑'
  dialogFormVisible.value = true
}

const saveGroupChange = () => {
  saveTemplateGroup()
}

const handleDeleteGroup = (scope) => {
  deleteTemplateGroup(tableData.value[scope.$index].pkid)
}

const routerToFile = (scope) => {
  router.push({
    name: 'templateList',
    query: {
      groupId: tableData.value[scope.$index].pkid
    }
  })
}
const routerToVar = (scope) => {
  router.push({
    name: 'templateVarList',
    query: {
      groupId: tableData.value[scope.$index].pkid
    }
  })
}

const deleteTemplateGroup = (id) => {
  instance.post('/templateGroup/deleteTemplateGroup?id=' + id).then((res) => {
    console.log(res)
    pageListTemplateGroup()
  }).catch((err) => {
    console.log(err)
  })
}

const saveTemplateGroup = () => {
  instance.post('/templateGroup/saveTemplateGroup', {
    pkid: form.pkid,
    groupName: form.groupName,
    groupDesc: form.groupDesc
  }).then((res) => {
    console.log(res)
    pageListTemplateGroup()
    dialogFormVisible.value = false
  }).catch((err) => {
    console.log(err)
  })
}

const pageListTemplateGroup = () => {
  instance.post('/templateGroup/pageListTemplateGroup', {
    pageNumber: 1,
    pageSize: 10
  }).then((res) => {
    console.log(res)
    tableData.value = [...res.data.data.records]
  }).catch((err) => {
    console.log(err)
  })
}

const generate = (scope) => {
  generateGroupId.value = tableData.value[scope.$index].pkid
  varListLoadingErrVarData.value = ''
  console.log('打开生成弹窗！！！')
  // 查询出变量
  listGroupVariableByGroupId({
    groupId: generateGroupId.value,
  }).then((res) => {
    console.log(res)
    varList.value = [...res.data.data]
    if (varList.value.length === 0) {
      varListLoadingErrMsg.value = '变量加载失败，你可以在下面写入你认为应当传入的变量和值(格式为json)⬇️⬇️';
    } else {
      generateForm.value = {}
      varList.value.forEach(field => {
        console.log(field.defaultValue)
        generateForm.value[field.variableName] = field.defaultValue || '';
      });
      varListLoadingErrMsg.value = ''
    }
    generateFrame.value = true
  }).catch((err) => {
    console.log(err)
    varListLoadingErrMsg.value = '变量加载失败，你可以在下面写入你认为应当传入的变量和值(格式为json)⬇️⬇️';
    generateFrame.value = true
  })
}

const submitGenerate = () => {
  instance.post('/codeGenerator/generate', {
    groupId: generateGroupId.value,
    dataModel: varListLoadingErrMsg.value ? JSON.parse(varListLoadingErrVarData.value) : generateForm.value
  }, {responseType: 'blob'}).then((res) => {
    console.log(res)
    postFileDownLoad(res)
    pageListTemplateGroup()
    generateFrame.value = false
  }).catch((err) => {
    console.log(err)
  })
}

const postFileDownLoad = (res) => {
  if (!res.data) {
    return;
  }
  const fileName = decodeURIComponent(
    res.headers["content-disposition"].split("filename=")[1]
  );
  const blob = new Blob([res.data], {
    type: "application/zip",
  });
  const downloadElement = document.createElement("a");
  const href = window.URL.createObjectURL(blob); // 创建下载的链接
  downloadElement.href = href;
  // 文件名中有中文 则对文件名进行转码
  downloadElement.download = fileName; // 下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); // 点击下载
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href); // 释放blob对象
}

onMounted(() => {
  pageListTemplateGroup()
})

</script>

<style scoped>


</style>
